import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:event_bus/event_bus.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:http/http.dart' as http;

// 1. 定义事件类型
class UserLoginEvent {
  final dynamic username;
  UserLoginEvent(this.username);
}

class UserLoginEvents {
  final dynamic username;
  UserLoginEvents(this.username);
}

// 2. 初始化全局总线
final EventBus eventBus = EventBus();

// void main() {
//   // 3. 订阅事件（通常在StatefulWidget的initState中）
//   final subscription = eventBus.on<UserLoginEvent>().listen((event) {
//     print('用户登录成功: ${event.username}');
//   });

//   // 4. 模拟登录成功后发布事件
//   simulateLogin();

//   // 5. 取消订阅（在dispose中调用）
//   Future.delayed(Duration(seconds: 1), () {
//     subscription.cancel();
//   });
// }

// void simulateLogin() {
//   eventBus.fire(UserLoginEvent('张伟'));
// }

// osg正式域名 https://api.gonghai.top
// 外网ipv4面板地址: http://120.26.170.230:29051/b22d1115
//  username: b3yvu8fh
//  password: b58a9087
// 服务器，h5放
// osg.gonghai.top
// 外网ipv4面板地址: http://121.196.247.54:41613/0b42688e
//  username: rsrslvix
//  password: acc94e9b
// 下载服务器

//var bsurl = 'https://osg1.wexiang.vip';
var bsurl = 'https://api.gonghai.top';

var baseUrl = 'http://osg.gonghai.top'; //三方兑换
final weburl = 'http://osg.gonghai.top'; //邀请域名

var downurl = 'http://osg.gonghai.top/osg.html'; //更新apk

var context;
con(contextx) {
  context = contextx;
}

delData({required url, data, load = true}) async {
  Uri surl;
  if (bsurl.startsWith("https")) {
    surl = Uri.https(bsurl.replaceAll('https://', ''), url, data);
  } else {
    surl = Uri.http(bsurl.replaceAll('http://', ''), url, data);
  }

  if (load) {
    // showDialog(
    //   context: context,
    //   barrierDismissible: false,
    //   builder: (context) {
    //     return const Center(
    //       child: CircularProgressIndicator(color: Colors.white),
    //     );
    //   },
    // );
  }

  var response = await http.delete(
    surl,
    headers: <String, String>{
      'Authorization': myget('token') ?? '',
      'Content-Type': 'application/json',
      'Accept': 'application/json',
    },
  );
  var res = jsonDecode(response.body); // 导入dart:convert
  return myResponse(response, res, load);
}

putData({required url, data, load = true, mtype}) async {
  var surl = Uri.parse('$bsurl$url');
  if (load) {
    // loading();
  }
  var response = await http.put(
    surl,
    body: data,
    headers: <String, String>{
      'Authorization': myget('token') ?? '',
      'Accept': 'application/json',
    },
  );
  var res = jsonDecode(response.body); // 导入dart:convert
  return myResponse(response, res, load);

  // if (response.statusCode == 200) {
  //   var data = jsonDecode(response.body); // 导入dart:convert
  //   print('Data: $data');
  // } else {
  //   print('Request failed: ${response.statusCode}');
  // }
}

getData({required url, data, load = true}) async {
  Uri surl;
  if (bsurl.startsWith("https")) {
    surl = Uri.https(bsurl.replaceAll('https://', ''), url, data);
  } else {
    surl = Uri.http(bsurl.replaceAll('http://', ''), url, data);
  }

  if (load) {
    // showDialog(
    //   context: context,
    //   barrierDismissible: false,
    //   builder: (context) {
    //     return const Center(
    //       child: CircularProgressIndicator(color: Colors.white),
    //     );
    //   },
    // );
  }

  var response = await http.get(
    surl,
    headers: <String, String>{
      'Authorization': myget('token') ?? '',
      'Content-Type': 'application/json',
      'Accept': 'application/json',
    },
  );
  var res = jsonDecode(response.body); // 导入dart:convert
  return myResponse(response, res, load);
}

money(princ) {
  return (princ ?? 0) / 100;
}

setInteger(lv, {double? w, double? h}) {
  if (lv == 1) {
    return wImage(url: 'lanv', width: w, height: h);
  } else if (lv == 2) {
    return wImage(url: 'hongv', width: w, height: h);
  } else if (lv == 3) {
    return wImage(url: 'huangv', width: w, height: h);
  } else if (lv == 4) {
    return wImage(url: 'lvv', width: w, height: h);
  } else {
    return Text('');
  }
}

loading() {
  showDialog(
    context: context,
    barrierDismissible: false,
    builder: (context) {
      return const Center(
        child: CircularProgressIndicator(color: Colors.white),
      );
    },
  );
}

postData({required url, data, load = true, mtype}) async {
  var surl = Uri.parse('$bsurl$url');
  if (load) {
    // loading();
  }
  var response = await http.post(
    surl,
    body: jsonEncode(data),
    headers: <String, String>{
      'Content-Type': 'application/json',
      'Authorization': myget('token') ?? '',
    },
  );
  var res = jsonDecode(response.body); // 导入dart:convert
  return myResponse(response, res, load);

  // if (response.statusCode == 200) {
  //   var data = jsonDecode(response.body); // 导入dart:convert
  //   print('Data: $data');
  // } else {
  //   print('Request failed: ${response.statusCode}');
  // }
}

myResponse(response, res, load) {
  // if (load) {
  //   Get.back();
  // }
  if (response.statusCode == 200) {
    if (res['code'] == 0) {
      return res['data'];
    } else {
      if (response.statusCode == 401) {
        Get.offAllNamed('/login/login_type');
      } else {
        if (load) {
          Get.back();
        }
        showTost(res['message'] ?? res['error']);
      }
    }
  } else {
    if (response.statusCode == 401) {
      Get.offAllNamed('/login/login_type');
    } else {
      showTost(res['message'] ?? res['error']);
      return;
    }
  }
}

showTost(text) {
  Timer(Duration(milliseconds: 60), () {
    Get.dialog(
      barrierColor: Colors.transparent,
      AlertDialog(
        backgroundColor: Colors.transparent,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5)),
        content: Container(
          alignment: Alignment.center,
          constraints: BoxConstraints(maxWidth: 300, maxHeight: 100),
          padding: EdgeInsets.symmetric(horizontal: 20, vertical: 20),
          decoration: BoxDecoration(
            color: Color(0X83000000),
            borderRadius: BorderRadius.circular(15),
          ),
          child: Text(
            text,
            style: TextStyle(fontSize: 16, color: Color(0XFFFFFFFF)),
          ),
        ),
      ),
    );
  });

  Future.delayed(Duration(seconds: 1), () {
    if (Get.isDialogOpen!) {
      // 确保对话框仍然打开
      Get.back(); // 关闭对话框
    }
  });
}

isdata() {
  return Container(
    alignment: Alignment.center,
    margin: EdgeInsets.only(top: 100),
    child: Text(
      '暂无数据',
      style: TextStyle(fontSize: 16, color: Color(0XFF999999)),
    ),
  );
}

PayWidget(text, type) {
  Get.dialog(
    AlertDialog(
      backgroundColor: Color(0XFFFFFFFF),
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
      content: Container(
        height: 80,
        width: 120,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Text(
              '$text',
              style: TextStyle(fontSize: 20),
              textAlign: TextAlign.center,
            ),
            // Text('是否前往开通？',style: TextStyle(fontSize:20)),
          ],
        ),
      ),
      actions: [
        GestureDetector(
          onTap: () {
            if (type == '1') {
              Get.back();

              toNamed('/certification');
            } else {
              Get.back();
              toNamed('/web_tabs/shopping/mall_wallet');
            }
          },
          child: Container(
            alignment: Alignment.center,
            margin: EdgeInsets.only(bottom: 20),
            padding: EdgeInsets.symmetric(horizontal: 15, vertical: 10),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular((35)),
              gradient: LinearGradient(
                colors: [Color(0xff2189E7), Color(0xffBF67F8)], // 定义颜色列表
                begin: Alignment.topLeft, // 渐变开始的位置
                end: Alignment.bottomRight, // 渐变结束的位置
              ),
            ),
            child: Text('确定', style: TextStyle(color: Color(0XFFFFFFFF))),
          ),
        ),
        GestureDetector(
          onTap: () {
            Get.back();
          },
          child: Container(alignment: Alignment.center, child: Text('取消')),
        ),
      ],
    ),
  );
}

myset(name, value) {
  final box = GetStorage();
  box.write(name, value);
}

myget(name) {
  final box = GetStorage();
  return box.read(name);
}

hao(String nftId) {
  if (nftId.isNotEmpty) {
    var len = 5 - nftId.length;
    for (var i = 0; i < len; i++) {
      nftId = '0$nftId';
    }
  }
  return nftId;
}

buildBackButton(BuildContext context) {
  // 始终显示返回按钮
  return IconButton(
    icon: Icon(Icons.arrow_back_ios, color: Colors.black),
    tooltip: '返回',
    onPressed: () {
      back();
    },
  );
}

back() {
  final bool routing = Get.routing.args ?? false;
  print(444444);
  print(routing);
  if (routing) {
    Get.back();
  } else {
    Get.offAllNamed('/');
  }
}

toNamed(url, [dynamic aparameters]) async {
  var res = await Get.toNamed(url, arguments: true, parameters: aparameters);
  return res;
}

simg(url, width, borderRadius, height, fit, color) {
  return Image.network(
    url,
    width: width,
    height: height,
    fit: fit,
    frameBuilder: (context, child, frame, wasSynchronouslyLoaded) {
      if (wasSynchronouslyLoaded || frame != null) {
        return child; // 图片已加载完成
      }
      return Container();
    },
    errorBuilder: (context, error, stackTrace) {
      return const Icon(Icons.error); // 错误占位
    },
  );
}

imga(url, width, borderRadius, height, fit, color) {
  return Image.asset(
    "images/$url.png",
    fit: fit,
    width: width,
    height: height,
    color: color,
    frameBuilder: (context, child, frame, wasSynchronouslyLoaded) {
      if (wasSynchronouslyLoaded || frame != null) {
        return child; // 图片已加载完成
      }
      return Container();
    },
    errorBuilder: (context, error, stackTrace) {
      return const Icon(Icons.error); // 错误占位
    },
  );
}

copy(BuildContext context, textToCopy) async {
  await Clipboard.setData(ClipboardData(text: textToCopy));
  showTost('已复制到剪贴板');
}

wImage({
  required String url,
  double? width,
  double borderRadius = 0,
  double? height,
  fit = BoxFit.cover,
  color,
}) {
  if (url.startsWith("http") || url.startsWith("https")) {
    if (borderRadius > 0) {
      return ClipRRect(
        borderRadius: BorderRadius.circular(borderRadius),
        child: simg(url, width, borderRadius, height, fit, color),
      );
    } else {
      return simg(url, width, borderRadius, height, fit, color);
    }
  } else {
    if (borderRadius > 0) {
      return ClipRRect(
        borderRadius: BorderRadius.circular(borderRadius),
        child: imga(url, width, borderRadius, height, fit, color),
      );
    } else {
      return Image.asset(
        "images/$url.png",
        fit: fit,
        width: width,
        height: height,
        color: color,
        frameBuilder: (context, child, frame, wasSynchronouslyLoaded) {
          if (wasSynchronouslyLoaded || frame != null) {
            return child; // 图片已加载完成
          }
          return Container();
        },
        errorBuilder: (context, error, stackTrace) {
          return const Icon(Icons.error); // 错误占位
        },
      );
      //return imga(url,width,borderRadius,height,fit,color);
    }
  }
}

wText({
  required String text,
  double? size = 12,
  String? color = '0F172B',
  textAlign = TextAlign.left,
  double? height,
  bold = false,
}) {
  Color colors = Color(int.parse('0xff$color'));
  if (bold) {
    return Text(
      text,
      style: TextStyle(
        fontSize: size,
        color: colors,
        fontWeight: FontWeight.bold,
        height: height,
      ),
      textAlign: textAlign,
    );
  } else {
    return Text(
      text,
      style: TextStyle(fontSize: size, color: colors, height: height),
      textAlign: textAlign,
    );
  }
}

wRgb() {
  return BoxDecoration(
    borderRadius: BorderRadius.circular(50),
    gradient: LinearGradient(
      colors: [Color(0XFF38EBFF), Color(0XFF7F00FF)],
      begin: Alignment.topLeft,
      end: Alignment.bottomRight,
    ),
  );
}

wCon({
  required text,
  color = '0F172B',
  double borderRadius = 50,
  click,
  rgb = false,
}) {
  Color colors = Color(int.parse('0xff$color'));
  return GestureDetector(
    onTap: () {
      click();
    },
    child: Container(
      padding: EdgeInsets.symmetric(horizontal: 25),
      margin: EdgeInsets.symmetric(horizontal: 15, vertical: 15),
      height: 50,
      decoration:
          rgb
              ? wRgb()
              : BoxDecoration(
                color: colors,
                borderRadius: BorderRadius.circular(borderRadius),
              ),
      child: text,
    ),
  );
}

wTan({required text, click}) {
  return Get.dialog(
    AlertDialog(
      backgroundColor: Colors.transparent,
      content: Stack(
        children: [
          wImage(url: 'tan', width: 250),
          Positioned(
            top: 80,
            left: 0,
            right: 0,
            child: Align(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  text,
                  GestureDetector(
                    onTap: () {
                      click();
                    },
                    child: Container(
                      height: 50,
                      margin: EdgeInsets.only(top: 50, bottom: 30),
                      alignment: Alignment.center,
                      width: 210,
                      decoration: BoxDecoration(
                        color: Color(0XFF0F172B),
                        borderRadius: BorderRadius.circular(50),
                      ),
                      child: Text(
                        '确认',
                        style: TextStyle(
                          fontSize: 16,
                          color: Color(0XFFFFFFFF),
                        ),
                      ),
                    ),
                  ),
                  GestureDetector(
                    onTap: () => {Get.back()},
                    child: Text(
                      '取消',
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    ),
  );
}

showqidai() {
  Get.dialog(
    AlertDialog(
      backgroundColor: Colors.transparent,
      content: Stack(
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(15.0),
            child: Image.asset(
              'static/qidai.png',
              width: 250,
              fit: BoxFit.fitWidth,
            ),
          ),
        ],
      ),
    ),
  );
}



//   if (asset != null) {
//     String name = asset;
//     if (!name.endsWith(".png") &&
//         !name.endsWith(".jpg") &&
//         !name.endsWith(".jpeg") &&
//         !name.endsWith(".gif")) {
//       name = "$name.png";
//     }
//     if (!name.startsWith("images/")) {
//       name = "images/$name";
//     }
//     return Image.asset(name,
//         fit: fit, width: width, height: height, color: color,
//         frameBuilder: (context, child, frame, wasSynchronouslyLoaded) {
//           if (wasSynchronouslyLoaded || frame != null) {
//             return child; // 图片已加载完成
//           }
//           return Container();
//         },
//         errorBuilder: (context, error, stackTrace) {
//           return const Icon(Icons.error); // 错误占位
//         },
//       );
//   }

//   if (url == null || url.isEmpty) {
//     return Container(width: width, height: height, color: color);
//   }

//   if (borderRadius != null && borderRadius > 0) {
//     ClipRRect(
//       borderRadius: BorderRadius.circular(borderRadius),
//       child: Image.network(url,width:width,height: height,fit: fit,
//        frameBuilder: (context, child, frame, wasSynchronouslyLoaded) {
//           if (wasSynchronouslyLoaded || frame != null) {
//             return child; // 图片已加载完成
//           }
//           return Container();
//         },
//         errorBuilder: (context, error, stackTrace) {
//           return const Icon(Icons.error); // 错误占位
//         },
//       ),
//     );
//   }

//   return Image.network(url,width:width,height: height,fit: fit,
//       frameBuilder: (context, child, frame, wasSynchronouslyLoaded) {
//         if (wasSynchronouslyLoaded || frame != null) {
//           return child; // 图片已加载完成
//         }
//         return Container();
//       },
//       errorBuilder: (context, error, stackTrace) {
//         return const Icon(Icons.error); // 错误占位
//       },
//   );
// }